from typing import Any, Dict, Optional
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
from pydantic import ValidationError
from fastapi.exceptions import RequestValidationError

class BaseException(Exception):
    """基础异常类"""
    def __init__(
        self,
        code: int = 500,
        message: str = "服务器内部错误",
        data: Optional[Any] = None
    ):
        self.code = code
        self.message = message
        self.data = data
        super().__init__(message)

class BusinessException(BaseException):
    """业务异常"""
    def __init__(
        self,
        message: str = "业务处理异常",
        code: int = 400,
        data: Optional[Any] = None
    ):
        super().__init__(code=code, message=message, data=data)

class AuthException(BaseException):
    """认证异常"""
    def __init__(
        self,
        message: str = "认证失败",
        code: int = 401,
        data: Optional[Any] = None
    ):
        super().__init__(code=code, message=message, data=data)

class PermissionException(BaseException):
    """权限异常"""
    def __init__(
        self,
        message: str = "权限不足",
        code: int = 403,
        data: Optional[Any] = None
    ):
        super().__init__(code=code, message=message, data=data)

class NotFoundException(BaseException):
    """资源不存在异常"""
    def __init__(
        self,
        message: str = "资源不存在",
        code: int = 404,
        data: Optional[Any] = None
    ):
        super().__init__(code=code, message=message, data=data)

async def exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """全局异常处理器"""
    if isinstance(exc, BaseException):
        return JSONResponse(
            status_code=exc.code,
            content={
                "code": exc.code,
                "message": exc.message,
                "data": exc.data
            }
        )
    
    if isinstance(exc, HTTPException):
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "code": exc.status_code,
                "message": str(exc.detail),
                "data": None
            }
        )
    
    if isinstance(exc, (ValidationError, RequestValidationError)):
        # 获取第一个错误消息
        errors = exc.errors()
        if errors:
            error = errors[0]
            # 获取错误类型
            error_type = str(error.get("type", ""))
            error_ctx = error.get("ctx", {})
            # 获取字段名
            field = error.get("loc", ["", ""])[-1]
            print(error_ctx, field)
            
            # 根据错误类型返回对应的中文错误消息
            if "min_length" in error_ctx:
                message = f"{field}长度不能小于{error.get('ctx', {}).get('min_length', '')}个字符"
            elif "max_length" in error_ctx:
                message = f"{field}长度不能超过{error.get('ctx', {}).get('min_length', '')}个字符"
            elif "password_mismatch" in error_type:
                message = "两次密码不一致"
            else:
                message = "数据验证错误111"
        else:
            message = "数据验证错误222"
            
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content={
                "code": status.HTTP_422_UNPROCESSABLE_ENTITY,
                "message": message,
                "data": None
            }
        )
    
    # 处理其他未预期的异常
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
            "message": str(exc) if str(exc) else "服务器内部错误",
            "data": None
        }
    )
